# -*- coding: utf-8 -*-
import re

from fastapi   import Depends, Request, HTTPException
from aiosqlite import Connection


email = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')


async def is_auth(request: Request):
    if request.cookies.get("id") == None:
        raise HTTPException(401, detail = "Invalid authorization data")


def has_auth():
    return Depends(is_auth)

def is_email(string: str) -> bool:
    return bool(email.fullmatch(string))


async def database(db: Connection):
    await db.execute('CREATE TABLE IF NOT EXISTS `forecasts` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `dateTime` TEXT, `temperature` REAL, `weatherCondition` TEXT, `regionId` NUMERIC)')
    await db.execute('CREATE TABLE IF NOT EXISTS `region_types` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT)')
    await db.execute('CREATE TABLE IF NOT EXISTS `regions` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `parentRegion` TEXT, `regionType` NUMERIC, `latitude` REAL, `longitude` REAL, "accountId" INTEGER)')
    await db.execute('CREATE TABLE IF NOT EXISTS `users` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `email` TEXT, `password` TEXT, `firstName` TEXT, `lastName` TEXT)')
    await db.execute('CREATE TABLE IF NOT EXISTS "weather" (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `measurementDateTime` TEXT, `regionId` NUMERIC, regionName TEXT, `temperature` REAL, `humidity` REAL, `windSpeed` REAL, `precipitationAmount` REAL, `weatherForecast` TEXT, `weatherCondition` TEXT)')

    await db.commit()